package com.example.a2032.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.a2032.R;
import com.example.a2032.Utils.RxBus;
import com.example.a2032.Utils.SharedPreferenceUtils;
import com.example.a2032.adapter.ViewPagerVerticalAdapter;
import com.example.a2032.entity.ActionData;
import com.example.a2032.entity.BleData;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import fragment.DateFragment;
import fragment.WatchBg2Fragment;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomePageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomePageFragment extends BaseFragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.viewpager_home)
    ViewPager2 viewpagerHome;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    ViewPagerVerticalAdapter viewPagerVerticalAdapter;
    private int homeItem;

    public HomePageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment HomePageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HomePageFragment newInstance() {
        HomePageFragment fragment = new HomePageFragment();
        Bundle args = new Bundle();
        //args.putString(ARG_PARAM1, param1);
        // args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);
        Log.i(TAG, "onCreateView: ");
        init();
        return view;
    }
    @BindArray(R.array.item_opString)
    String[]opNames;
    int currentPosition;
    int homePageIndex=4;
    private void init() {

        List<Fragment>list=getFragment();
        viewPagerVerticalAdapter = new ViewPagerVerticalAdapter(this,list,200);
        viewpagerHome.setAdapter(viewPagerVerticalAdapter);
        homeItem=getStartItem(list.size())+homePageIndex;
        viewpagerHome.setCurrentItem(homeItem);
        viewpagerHome.registerOnPageChangeCallback(
                new ViewPager2.OnPageChangeCallback() {
                    @Override
                    public void onPageSelected(int position) {
                        super.onPageSelected(position);
                        onPageChangeListener.setUserInputEnabled(position%list.size() == homePageIndex);
                        currentPosition=position;
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        super.onPageScrollStateChanged(state);
//                        if (state == ViewPager2.SCROLL_STATE_IDLE) {
//                            if (currentPosition == 0) {
//                                viewpagerHome.setCurrentItem(list.size() - 2, false);//切换，不要动画效果
//                            } else if (currentPosition == list.size() - 1) {
//                                viewpagerHome.setCurrentItem(1, false);//切换，不要动画效果
//                            }
//                        }
                    }


                }
        );
        subscribe();
    }
    private int getStartItem(int size) {

        if(size == 0){
            return 0;
        }
        // 我们设置当前选中的位置为Integer.MAX_VALUE / 2,这样开始就能往左滑动
        // 但是要保证这个值与getRealPosition 的 余数为0，因为要从第一页开始显示
        int currentItem = size * 200 / 2;
        if(currentItem % size ==0 ){
            return currentItem;
        }
        // 直到找到从0开始的位置
        while (currentItem % size != 0){
            currentItem++;
        }
        return currentItem;


    }

    private List<Fragment> getFragment() {
        int length=opNames.length;
        homePageIndex=length==7?4:5;
        List<Fragment> list = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            if (i == homePageIndex) {
                list.add(getWatchStylePage());
            }
            list.add(OpFragment.newInstance(i));
        }

        return list;
    }

    private static final String TAG = "HomePageFragment";
    Disposable disposable;

    protected void subscribe() {
        RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BleData>() {
            @Override
            public void onSubscribe(Disposable d) {
                disposable = d;
            }

            @Override
            public void onNext(BleData bleData) {
                String action = bleData.getAction();
                if (action.equals(ActionData.ChangeWatchStyle)) {
                    Log.i(TAG, "onNext: ");
                    viewPagerVerticalAdapter.updateData(getFragment());
                } else if (action.equals(ActionData.BackToHome)) {
                    viewpagerHome.setCurrentItem(homeItem,false);
                }

            }


            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    private BaseFragment getWatchStylePage() {
        BaseFragment watchPage = null;
        int currentWatchFace = SharedPreferenceUtils.getInteger(SharedPreferenceUtils.KEY_WatchFace, 0);
        switch (currentWatchFace) {
            case 0:
                watchPage = DateFragment.newInstance();
                break;
            case 1:
                watchPage = WatchBgFragment.newInstance();
                break;
            case 2:
                watchPage = WatchBg2Fragment.newInstance();
                break;
        }
        return watchPage;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        onPageChangeListener = (OnPageChangeListener) context;
    }

    OnPageChangeListener onPageChangeListener;

    public interface OnPageChangeListener {
        public void setUserInputEnabled(boolean enable);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.i(TAG, "onHiddenChanged: " + hidden);

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
    }
}